package com.zlp.mall.modules.ums.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zlp.mall.common.api.Pager;
import com.zlp.mall.common.api.R;
import com.zlp.mall.common.redis.RedisService;
import com.zlp.mall.common.util.JwtTokenUtil;
import com.zlp.mall.modules.ums.dto.UpdateAdminPasswordParam;
import com.zlp.mall.modules.ums.dto.req.AddAdminReq;
import com.zlp.mall.modules.ums.dto.req.AdminLoginReq;
import com.zlp.mall.modules.ums.dto.resp.AdminResp;
import com.zlp.mall.modules.ums.model.Admin;
import com.zlp.mall.modules.ums.model.UmsRole;
import com.zlp.mall.modules.ums.service.AdminService;
import com.zlp.mall.modules.ums.service.UmsRoleService;
import com.zlp.mall.security.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户管理
 *
 * @author ZouLiPing
 * @since 2021-9-17 10:47:37
 */
@RestController
@Api(value = "AdminController", tags = "后台用户管理")
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;
    @Autowired
    private UmsRoleService roleService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Resource
    private RedisService redisService;

    @PostMapping(value = "/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public R<AdminResp> register( @RequestBody @Valid AddAdminReq addAdminReq) {

        return R.success(adminService.register(addAdminReq));
    }

    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping(value = "/login")
    public R login(@Valid @RequestBody AdminLoginReq adminLoginReq) {

        Admin login = adminService.login(adminLoginReq.getUsername(), adminLoginReq.getPassword());
        String token = jwtTokenUtil.generateTokenByUserName(login.getUsername());
        Map<String,Object> map = new HashMap<>(3);
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        map.put("username",login.getUsername());
        return R.success(map);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value = "获取当前登录用户信息", notes = "获取当前登录用户信息")
    public R getAdminInfo() {

        Admin admin = SecurityUtils.getUser();
        Map<String, Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("menus", roleService.getMenuList(admin.getId()));
        data.put("icon", admin.getIcon());
        List<UmsRole> roleList = adminService.getRoleList(admin.getId());
        if (CollUtil.isNotEmpty(roleList)) {
            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
            data.put("roles", roles);
        }
        return R.success(data);
    }

    @PostMapping(value = "/logout")
    @ApiOperation(value = "登出功能", notes = "登出功能")
    public R logout(HttpServletRequest request) {

        String jwt = request.getHeader(tokenHeader);
        //判断是否存在 判断开头是否加了tokenHead Bearer
        if (StrUtil.isNotBlank(jwt) && jwt.startsWith(tokenHead)) {
            jwt = jwt.substring(tokenHead.length());
            redisService.del(jwt);
        }
        return R.success();
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "根据关键字分页获取用户列表", notes = "根据关键字分页获取用户列表")
    public R<Pager<AdminResp>> list(
            @RequestParam(value = "keyword", required = false) @ApiParam(name="keyword",value="关键字") String keyword,
            @RequestParam(value = "pageSize", defaultValue = "5") @ApiParam(name="pageSize",value="每页多少条",required = true) Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") @ApiParam(name="pageNum",value="当前第几页(从第一页开始)",required = true) Integer pageNum
    ) {

        return R.success(adminService.list(keyword, pageSize, pageNum));
    }

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取指定用户信息", notes = "根据关键字分页获取用户列表")
    public R<Admin> getItem(@PathVariable Long id) {
        Admin admin = adminService.getById(id);
        return R.success(admin);
    }

    @PostMapping(value = "/update/{id}")
    @ApiOperation(value = "修改指定用户信息", notes = "修改指定用户信息")
    public R update(@PathVariable Long id, @RequestBody Admin admin) {
        boolean success = adminService.update(id, admin);
        if (success) {
            return R.success(null);
        }
        return R.failed();
    }

    @PostMapping(value = "/updatePassword")
    @ApiOperation(value = "修改用户密码", notes = "修改用户密码")
    public R updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updatePasswordParam) {
        int status = adminService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return R.success(status);
        } else if (status == -1) {
            return R.failed("提交参数不合法");
        } else if (status == -2) {
            return R.failed("找不到该用户");
        } else if (status == -3) {
            return R.failed("旧密码错误");
        } else {
            return R.failed();
        }
    }

    @PostMapping(value = "/delete/{id}")
    @ApiOperation(value = "删除用户信息", notes = "删除用户信息")
    public R delete(@PathVariable Long id) {
        boolean success = adminService.delete(id);
        if (success) {
            return R.success(null);
        }
        return R.failed();
    }

    @PostMapping(value = "/updateStatus/{id}")
    @ApiOperation(value = "修改帐号状态", notes = "修改帐号状态")
    public R updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
        Admin umsAdmin = new Admin();
        umsAdmin.setStatus(status);
        boolean success = adminService.update(id, umsAdmin);
        if (success) {
            return R.success(null);
        }
        return R.failed();
    }

    @PostMapping(value = "/role/update")
    @ApiOperation(value = "给用户分配角色", notes = "给用户分配角色")
    public R updateRole(@RequestParam("adminId") Long adminId,
                        @RequestParam("roleIds") List<Long> roleIds) {
        int count = adminService.updateRole(adminId, roleIds);
        if (count >= 0) {
            return R.success(count);
        }
        return R.failed();
    }

    @GetMapping(value = "/role/{adminId}")
    @ApiOperation(value = "获取指定用户的角色", notes = "获取指定用户的角色")
    public R<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
        List<UmsRole> roleList = adminService.getRoleList(adminId);
        return R.success(roleList);
    }
}
